import { request } from "../../utils/http";

Page({
  data: {
    id: 0,
    order: {},
    user: {
      id: "",
      mobile: "",
      name: "张三",
    },
    timeout: "",
    confirmCancelShow: false,
    isLoadPlugin: false,
    smid: "",
    kefu_show: 0,
    after_sales_hidden: 0,
    chain_initiative_pay: 0,
    zm_initiative_pay: 0,
    card_initiative_pay: 0,
    wechat_initiative_pay: 0,
    outOrderNo:''
  },
  callStore() {
    my.makePhoneCall({
      number: this.data.order.store.service_phone,
      success() {
        console.log("success", arguments);
      },
      fail() {
        console.log("fail");
      },
    });
  },
  onLoad(query) {
    // 页面加载
    //console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
    // debugger
    console.log(query, 'canshu')
    
    this.setData({
      id: query.id || 0,
      outOrderNo:query.outOrderNo || ''

    },() => {
      this.fetch(query.id || 0);
    });
  },
  onReady() {
    // 页面加载完成
  },
  onShow(query) {
    console.log(this, query)
    // my.getStorage({
    //   key: "kefu_show",
    //   success: (res) => {
    //     if (res.data) {
    //       this.setData({
    //         kefu_show: res.data,
    //       });
    //     }
    //   },
    // });

    // my.getStorage({
    //   key: "after_sales_hidden",
    //   success: (res) => {
    //     if (res.data) {
    //       this.setData({
    //         after_sales_hidden: res.data,
    //       });
    //     }
    //   },
    // });

    // my.getStorage({
    //   key: "chain_initiative_pay",
    //   success: (res) => {
    //     if (res.data) {
    //       this.setData({
    //         chain_initiative_pay: res.data,
    //       });
    //     }
    //   },
    // });

    // my.getStorage({
    //   key: "zm_initiative_pay",
    //   success: (res) => {
    //     if (res.data) {
    //       this.setData({
    //         zm_initiative_pay: res.data,
    //       });
    //     }
    //   },
    // });

    // my.getStorage({
    //   key: "card_initiative_pay",
    //   success: (res) => {
    //     if (res.data) {
    //       this.setData({
    //         card_initiative_pay: res.data,
    //       });
    //     }
    //   },
    // });

    // if (this.data.id  &&  this.data.id != 0) {
    //   this.fetch(this.data.id);

    // }
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: "",
      desc: "",
      path: "pages/index/index",
    };
  },
  goService() {
    my.navigateTo({
      url: "/pages/kefu/kefu",
    });
  },
  viewDoc() {
    my.showLoading();
    my.downloadFile({
      url: this.data.order.contract_download_url,
      success({ apFilePath }) {
        my.hideLoading();
        my.openDocument({
          filePath: apFilePath,
          fileType: "pdf",
          success() { },
          fail() { },
        });
      },
      fail() {
        my.hideLoading();
      },
    });
  },
  fetch(id) {
    let params = {}
    if (this.data.outOrderNo) {
      params['outOrderNo'] = this.data.outOrderNo
    }
    request("/order/" + id, "get", params).then((res) => {
      if (res.code == 200) {
        my.setStorageSync({ key: 'is_skip_bindcard', data: res.data.is_skip_bindcard || 0 })

        this.setData({
          order: res.data,
        },
        );
        // if (res.data.shop.shop_pay_type == 3) {
        //   my.setNavigationBar({
        //     title:'订单详情',
        //   })
        // }
        if (res.data.timeout && res.data.timeout > 0) {
          this.changeTimeout(res.data.timeout);
        }
        this.getConfig(res.data.shop.id)

        request("/shop/smid", "get", {shop_id: res.data.shop.id }).then((res) => {
          if (res.code == 200) {
            this.setData({
              smid: res.data.smid,
            },() => {
              this.loadPlugin();
            });
          }
        });
      }

    });
  },
  breakApply(e) {
    const id = e.target.dataset.id;
    my.navigateTo({ url: "../orderBreak/index?order_id=" + id });
  },
  payStage(e) {
    let self = this;
    const id = e.target.dataset.id;
    const item = e.target.dataset.item;

    // my.navigateTo({
    //   url: `/pages/coupon-confirm/coupon-confirm?id=${id}&price=${item.amount}&no=${item.no}&order_id=${this.data.order.id}`
    // })
    request(`/order/voluntary_repayment/${id}`, "post").then((res) => {
      if (res.code == 200) {
        let trade_no = res.data.trade_no;
        my.tradePay({
          tradeNO: trade_no,
          success(result) {
            console.log(result, "success");
            self.getOrderStageStatus(id);
          },
          fail(error) {
            console.log(error, "error");
          },
        });
      } else {
        my.showToast({ content: res.message });
      }
    });
  },
  getOrderStageStatus(order_id) {
    request("/order/stage/pay_result/" + order_id, "get", {
      queryStatus: 1,
    }).then((res) => {
      if (res.code == 200) {
        my.redirectTo({
          url: `/pages/pay-result/pay-result?id=${this.data.order.id}&status=${res.data.status}`,
        });
      } else {
        my.showToast({ content: res.message });
      }
    });
  },
  breakCancel(e) {
    this.setData({
      confirmCancelShow: true,
    });
  },
  saveBreakCancel() {
    request("/order/breakCancel", "post", {
      order_id: this.data.id,
    }).then((res) => {
      this.confirmCancelShow = false;
      this.fetch(this.data.id);
      my.navigateTo({
        url: "../breakCanceResult/index?order_id=" + this.data.id,
      });
    });
  },
  handleButtonTap(index) {
    if (index === 0) {
      this.setData({
        confirmCancelShow: false,
      });
    } else {
      this.saveBreakCancel();
    }
  },

  /**
   *	调用跳转方法
   */
  orderQuery() {
    if (this.data.order.version == 4) {
      my.navigateToMiniProgram({
        appId: '2021004147687320',
        path: `/pages/cycle-card-detail/index?outOrderNo=${this.data.order.out_order_no}`,
        success: () => {
          console.log('navigateToMiniProgram success');
        },
        fail: res => {
          my.alert({
            title: 'navigateToMiniProgram fail',
            content: JSON.stringify(res),
          });
        },
      });
    } else {
      if (!this.data.isLoadPlugin) {
        my.showToast({ content: "插件加载失败" });
        return;
      }
  
      this.initData(this.data.order);
      // 跳转至插件首页
      my.navigateTo({
        url: "dynamic-plugin://2021003126645865/index",
      });
    }
  },

  /**
   *	初始化数据 - 宿主传参
   */

  loadPlugin() {
    console.log("loadPlugin");
    my.loadPlugin({
      plugin: "2021003126645865@*", // 指定要加载的插件id和版本号，为 * 时自动选择版本
      success: () => {
        // 初始化数据 - 宿主传参
        console.log("success");
        this.setData({
          isLoadPlugin: true,
        });
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },

  initData(order) {
    // 引用插件实例
    const plugin = requirePlugin("dynamic-plugin://2021003126645865");
    const ext = my.getExtConfigSync();

    //plugin.setEnv('dev');
    let queryOptions = {
      merchantPid: this.data.smid, // 必传 - 商户PID
      productNo: this.data.order.product_id, // 必传 - 产品编号
      subscriptionNo: this.data.order.order_no, //必传 - 订购编号
    }
    if (order.shop.ant_shopid) {
      queryOptions['shopId'] = order.shop.ant_shopid
    }
    // 查询
    plugin.init({
      queryOptions: queryOptions,
    });
  },
  getOrderStatus(order_id) {
    request("/order/" + order_id, "get", { queryStatus: 1 }).then((res) => {
      if (res.code == 200) {
        my.redirectTo({
          url: `/pages/pay-result/pay-result?id=${order_id}&status=${res.data.status}`,
        });
      } else {
        my.showToast({ content: res.message });
      }
    });
  },
  schemeToParams(scheme) {
    console.log(scheme)
    if (!scheme.startsWith('alipays:')) {
      return { message: '! 非 alipays: 开头' };
    }
    var params = {};
    var parseQuery = (str) => {
      return str.replace(/^.*?\?/, '').split('&').map(s => {
        var p = s.includes('=') ? s.indexOf('=') : s.length;
        return [s.slice(0, p), s.slice(p + 1)].map(decodeURIComponent);
      });
    };
    for (var [k, v] of parseQuery(scheme)) {
      if (k == 'appId') {
        if (v.length != 16) {
          return { message: `! 非 16 位 appId '${v}'` };
        }
      } else if (k == 'page') {
        k = 'path';
      } else if (k == 'query') {
        var o = {};
        for (var [x, y] of parseQuery(v)) {
          o[x] = y;
        }
        v = o;
      } else {
        // return { message: `! 不支持参数 '${k}' ` };
      }
      params[k] = v;
    }
    return params;
  },
  goNext(){
    my.setStorageSync({
      data: this.data.id,
      key: 'blockchain_id'
    });
    my.navigateToMiniProgram({
      appId: "2021001152620480", // 固定值，无须修改。

      path: "pages/tripartite/index", // 固定值，无须修改。

      query: {
        signStr: this.data.sign_str, // 代扣签约创建接口返回的sign_str内容

        tenantId: this.data.tenantId, // 商家的用户code，在数科控制台中查询获取

        merchantId: this.data.merchantId, // 商户id,也是企业社会信用代码，保持与进件接口一致

        orderId: this.data.orderNo, // // 订单id，保持与进件接口一致

        redirectUrl:
          "alipays://platformapi/startapp?appId=2021004141663044&page=pages/blockchain-result/blockchain-result?order_id=" + this.data.id, // 代扣签署成功/失败回跳地址，示例 alipays://platformapi/startapp?appId=2021004108689505&page=pages/home/index，appId 和 page 需要根据实际情况调整真实数值
      }, // 需要携带的必要参数

      success: () => {},

      fail: () => {},
    });
  },
  reOrder() {
    let order = this.data.order;
    let self = this;
    if (order.mixed_order == 1) {
      if (order.jump_type == 1) {
        let trade_no = order.stage_list[0].order_no;
        my.tradePay({
          tradeNO: trade_no,
          success(result) {
            console.log(result)
            request('/order/stage/pay_result/' + order.stage_list[0].id, 'get', { queryStatus: 1 }).then(orderRes => {
              if (orderRes.code == 200) {
                my.navigateTo({
                  url: `/pages/mixed-result/mixed-result?status=${orderRes.data.status}&order_no=${order.id}&price=${order.mixed_order_pre_price}`
                })
              }
            })


          },
          fail(error) {
            console.log(error, 'error')
            my.navigateTo({
              url: `/pages/mixed-result/mixed-result?status=50&order_no=${order.id}`
            })
          }
        })
      } else {
        if (order.version == 4) {
          this.goZM4(order)
        } else {
          this.goPlugin(order, 1);
        }

      }
    } else {
      if (order.shop.shop_pay_type == 3) {
        if (order.pay_method == 1) {
          let trade_no = order.order_no;
          my.tradePay({
            tradeNO: trade_no,
            success(result) {
              console.log(result, "success");
              if (result.resultCode == '9000') {
                self.getOrderStatus(order.id);

              } else {
                my.showToast({ content: result.memo });
              }
              // self.getOrderStatus(order.id);
            },
            fail(error) {
              console.log(error, "error");
            },
          });
        } else {
          if (order.contract_flow_status == 2) {
            my.navigateTo({
              url: "/pages/bind-bank/bind-bank?id=" + order.id + "&type=1",
            });
          } else {
            my.navigateTo({
              url: `/pages/bind-bankInfo/bind-bankInfo?id=${order.id}`,
            });
          }
        }

      } else {
        if (order.pay_method == 1) {
          let trade_no = order.order_no;
          my.tradePay({
            tradeNO: trade_no,
            success(result) {
              console.log(result, "success");
              if (result.resultCode == '9000') {
                self.getOrderStatus(order.id);

              } else {
                my.showToast({ content: result.memo });
              }
            },
            fail(error) {
              console.log(error, "error");
            },
          });
        } else if (order.pay_method == 2) {
          let url = this.data.order.ant_new_sign_url;

          let params = this.schemeToParams(url);

          if (params) {
            my.navigateToMiniProgram({
              ...params,
              fail: (res) =>
                my.alert({
                  title: "跳转小程序失败",
                  content: JSON.stringify(res),
                }),
            });
          }
        } else {
          let aiqian_zm = my.getStorageSync({ key: "aiqian_zm" }).data;
          if (aiqian_zm == 1) {
            if (order.contract_flow_status == 2) {
              if (order.version == 4) {
                this.goZM4(order)
              } else {
                this.goPlugin(order);
              }
            } else {
              my.setStorageSync({
                data: order.id,
                key: "sign_order_id",
              });
              my.removeStorageSync({ key: "sign_order_type" });

              my.navigateTo({
                url: `/pages/sign-webview/sign-webview?url=${order.contract_signurl}`,
              });
            }
          } else {
            if (order.version == 4) {
              this.goZM4(order)
            } else {
              this.goPlugin(order);
            }
          }
        }
      }
    }
  },

  goZM4(data){
    const accountInfo = my.getAccountInfoSync();
    const targetUrl = encodeURIComponent('/pages/zhima-result/zhima-result');
    let url =`/pages/cycle-card-buy/index?spcTemplateId=${data.card_template_id}&outOrderNo=${data.out_order_no}&shopId=${data.zm_shop_id}&jumpType=merchant&appId=${ accountInfo.miniProgram.appId || ''}&targetUrl=${targetUrl}`
    if (data.card_property_id) {
      url = `${url}&propertyId=${data.card_property_id}`
    }
    console.log(url)
    // return
    my.navigateToMiniProgram({
      appId: '2021004147687320',
      path: url,
      success: () => {
        console.log('navigateToMiniProgram success');
      },
      fail: res => {
        my.alert({
          title: 'navigateToMiniProgram fail',
          content: JSON.stringify(res),
        });
      },
    });
  },
  goPlugin(order, isMixed = 0) {
    // 引用插件实例
    const plugin = requirePlugin("dynamic-plugin://2021003126645865");
    const ext = my.getExtConfigSync();
    const options = {
      merchantPid: this.data.smid, // 必传 - 商户PID
      productNo: order.product_id, // 必传 - 产品编号

      subscriptionType: order.pay_date == 1 ? "MONTH" : "WEEK", // 非必填, 订购类型, 默认为月卡
      productName: order.product_title, //必传 - 产品名称
      deductionAmount: order.second_amount, // 必传 - 每次扣减固定金额
      periods: order.total_stage, // 必传 - 开通总周期数
      downPayment: order.first_amount, // 非必填 - 前N期金额
      downPaymentPeriods: order.first_stage, // 非必填 -前多少期价格不一样，不传默认为1
      downPaymentDate: order.stage_list[isMixed].date,
      outSubscriptionNo: order.out_order_no,
    };
    if (order.shop.ant_shopid) {
      options['shopId'] = order.shop.ant_shopid
    }
    plugin.init({
      openOptions: options,
    });
    // 跳转至插件首页
    my.navigateTo({
      url: "dynamic-plugin://2021003126645865/index",
    });
  },
  changeTimeout(timeout) {
    setTimeout(() => {
      if (timeout <= 0) {
        return;
      }
      let h = Math.floor(timeout / 3600);
      let m = Math.floor(timeout / 60);
      let s = timeout - m * 60;
      this.setData({
        timeout: `${m}分${s}秒`,
      });
      this.changeTimeout(timeout - 1);
    }, 1000);
  },
  goComplaint() {
    my.navigateTo({
      url: `/pages/complaint/add/add?order_id=${this.data.id}&mobile=${this.data.order.member.mobile}&pay_method=${this.data.order.pay_method}`,
    });
  },
  goBind() {
    my.setStorageSync({ key: 'is_skip_bindcard', data: 0 })

    my.navigateTo({
      url: `/pages/bind-bank/bind-bank?id=${this.data.order.id}&order_no=${this.data.order.out_order_no}&bind=1`,
    });
  },
  async getConfig(shop_id) {
    let res = await request('/shop/getSwitchConfigs','get', {shop_id: shop_id})
    if (res.code === 200) {
      console.log(res.data)
      // this.globalData.logo = res.data.app_logo
      // this.globalData.mobile_login = res.data.mobile_login

      my.setStorage({
        key:'supplier_id',
        data: res.data.supplier_id
      })

      my.setStorage({
        key: 'mobile_login',
        data: res.data.mobile_login,
        
      })

      my.setStorage({
        key: 'chain_initiative_pay',
        data: res.data.chain_initiative_pay,
        
      })
      

      my.setStorage({
        key: 'zm_initiative_pay',
        data: res.data.zm_initiative_pay,
        
      })
      

      my.setStorage({
        key: 'card_initiative_pay',
        data: res.data.card_initiative_pay,
        
      })

      my.setStorage({
        key: 'after_sales_hidden',
        data: res.data.after_sales_hidden,
        
      })

      my.setStorage({
        key: 'aiqian_zm',
        data: res.data.aiqian_zm,
        
      })

      my.setStorage({
        key: 'aiqian_card',
        data: res.data.aiqian_card,
        
      })

      my.setStorage({
        key:'kefu_show',
        data: res.data.kefu_show
      })

      my.setStorage({
        key:'card_pay_identity_no_required',
        data: res.data.card_pay_identity_no_required 
      })
      

      my.setStorage({
        key:'appointment_entrance',
        data: res.data.appointment_entrance 
      })

      my.setStorage({
        key:'wechat_initiative_pay',
        data: res.data.wechat_initiative_pay 
      })
      
      this.setData({
        zm_initiative_pay:res.data.zm_initiative_pay,
        chain_initiative_pay: res.data.chain_initiative_pay,
        card_initiative_pay: res.data.card_initiative_pay,
        after_sales_hidden: res.data.after_sales_hidden,
        kefu_show:res.data.kefu_show,
        wechat_initiative_pay:res.data.wechat_initiative_pay
      })
      
    }
  }
});
